package com.yict.common.query.core;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import com.yict.common.Constants;
import com.yict.common.util.ContextUtil;
import com.yict.common.util.StringUtil;

/**
 * <h3>Class name</h3> 查询存储介质处理类 <h4>Description</h4>
 * 
 * <h4>Special Notes</h4>
 * 
 * 
 * @version 1.0
 * @author Jay.Wu 2009-11-2
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class QueryInfoUtil {
	protected final Log logger = LogFactory.getLog(getClass());

	private static JdbcTemplate jdbcTemplate;

	private static QueryInfoUtil queryInfoUtil;

	private final static boolean fromDatabase = false;

	private static Map<String, String> map;

	private QueryInfoUtil(QueryUtil queryUtil) {
		if (jdbcTemplate == null && fromDatabase) {
			String sqlitePath = null;

			sqlitePath = this.getClass().getClassLoader().getResource("")
					.toString().substring(6)
					+ "query_info.sqlite";

			logger.info("jdbcTemplate is null! start init sqlite:\n "
					+ sqlitePath);
			if (StringUtil.isNotBlank(Constants.QUERYINFO_PATH)
					&& !Constants.QUERYINFO_PATH.equalsIgnoreCase("auto")) {
				sqlitePath = Constants.QUERYINFO_PATH;
			}

			try {
				sqlitePath = URLDecoder.decode(sqlitePath, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage(), e);
			}

			logger.info("Constants.QUERYINFO_PATH:\n " + sqlitePath);

			jdbcTemplate = new JdbcTemplate(
					new org.springframework.jdbc.datasource.DriverManagerDataSource(
							"org.sqlite.JDBC", "jdbc:sqlite:" + sqlitePath, "",
							""));
		} else {
			if (map == null) {
				map = new HashMap<String, String>();
				initMap();
			}
		}
	}

	private void initMap() {
		Map<String, Object> queryMap = (Map<String, Object>) ContextUtil.getBeanObject("query");

		if (queryMap != null) {
			for (String key : queryMap.keySet()) {
				Object object = queryMap.get(key);

				if (object instanceof String) {
					map.put(key, (String) object);
				} else {
					map.putAll((Map<String, String>) object);
				}
			}
		}
	}

	public static void findQueryInfoByKey(QueryUtil queryUtil) {
		queryInfoUtil = queryInfoUtil == null ? new QueryInfoUtil(queryUtil) : queryInfoUtil;
		if (fromDatabase) {
			String sql = "SELECT * FROM SYS_QUERY_INFO WHERE (QUERY_KEY = ? OR ID = ?) AND IS_OPEN = ?";
			Map queryInfo = jdbcTemplate.queryForMap(sql,
					new Object[] { queryUtil.getQueryKey(), queryUtil.getQueryId(), Constants.YES });
			queryUtil.setQueryType((String) queryInfo.get("QUERY_TYPE"));
			queryUtil.setQueryString((String) queryInfo.get("QUERY_STRING"));
		} else {
			if (queryUtil.getQueryKey().toLowerCase().lastIndexOf("_sql") > -1) {
				queryUtil.setQueryType("sql");
			}
			queryUtil.setQueryString(map.get(queryUtil.getQueryKey()));
		}
	}
}
